import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/HomeView.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/RegisterView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/UserProfileView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/admin/users',
    name: 'UserManagement',
    component: () => import('@/views/UserManagementView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/users/edit/:id',
    name: 'UserEdit',
    component: () => import('@/views/UserEditView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/DashboardView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFoundView.vue')
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 动态导入 userStore 避免循环依赖
  const { useUserStore } = await import('@/stores/user')
  const userStore = useUserStore()
  
  // 如果 store 中没有当前用户但 localStorage 有 token，尝试恢复用户状态
  if (!userStore.currentUser && userStore.token) {
    await userStore.fetchCurrentUser()
  }

  const isLoggedIn = userStore.isLoggedIn
  const userRole = userStore.userRole

  console.log('路由守卫检查:', { 
    to: to.path, 
    isLoggedIn, 
    userRole,
    requiresAuth: to.meta.requiresAuth,
    requiresAdmin: to.meta.requiresAdmin
  })

  if (to.meta.requiresAuth && !isLoggedIn) {
    console.log('需要登录，跳转到登录页')
    next('/login')
  } else if (to.meta.requiresGuest && isLoggedIn) {
    console.log('已登录用户访问游客页面，跳转到首页')
    next('/')
  } else if (to.meta.requiresAdmin && userRole !== 'admin') {
    console.log('非管理员访问管理员页面，跳转到首页')
    next('/')
  } else {
    console.log('允许访问:', to.path)
    next()
  }
})

export default router